package org.jingouzhui.domain.strategy.service.rule.tree;

import lombok.extern.slf4j.Slf4j;
import org.jingouzhui.domain.strategy.model.valboj.RuleLogicCheckTypeVO;
import org.jingouzhui.domain.strategy.model.valboj.StrategyAwardStockKeyVO;
import org.jingouzhui.domain.strategy.repository.IStrategyRepository;
import org.jingouzhui.domain.strategy.service.armory.StrategyArmoryDispatch;
import org.jingouzhui.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @description: 库存判定树节点
 * @author: jingouzhui
 * @date: 2025/5/1 16:45
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements  ILogicTreeNode{

    @Resource
    private StrategyArmoryDispatch strategyArmoryDispatch;

    @Resource
    private IStrategyRepository strategyRepository;
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId,String ruleValue) {
        log.info("规则树-库存扣减流程开始,userId:{},strategyId:{},awardId:{}",userId,strategyId,awardId);
        Boolean result = strategyArmoryDispatch.subtractionAwardStock(strategyId, awardId);
        if (result) {
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
            //写入延迟队列定时扣减数据库的值
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .awardId(awardId)
                    .strategyId(strategyId)
                    .build());
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }
        // 如果库存不足，则直接返回放行
        log.warn("规则过滤-库存扣减-告警，库存不足。userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckTypeVO(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
